﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace NanoMvvm.ComponentModel
{
    internal sealed class DynamicViewModelTypeDescriptor : CustomTypeDescriptor
    {
        private readonly WeakReference<IDynamicObject> targetInstance;

        internal DynamicViewModelTypeDescriptor(ICustomTypeDescriptor baseDescriptor, IDynamicObject instance)
            : base(baseDescriptor)
        {
            targetInstance = new WeakReference<IDynamicObject>(instance);
        }

        public static void Register<T>(DynamicViewModel<T> instance) where T : class
        {
            // assign the one provider to this instance
            TypeDescriptor.AddProvider(new DynamicViewModelTypeDescriptionProvider(instance.GetType()), instance);
        }

        public override PropertyDescriptorCollection GetProperties()
        {
            var props = base.GetProperties();

            IEnumerable<PropertyDescriptor> other = new PropertyDescriptor[] { };

            if (targetInstance.IsTargetAlive)
            {
                other = targetInstance.Target.GetDynamicPropertyDescriptors();
            }

            return new PropertyDescriptorCollection(props.Cast<PropertyDescriptor>().Concat(other).ToArray());
        }

        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            var props = base.GetProperties(attributes);

            IEnumerable<PropertyDescriptor> other = new PropertyDescriptor[] { };

            if (targetInstance.IsTargetAlive)
            {
                other = targetInstance.Target.GetDynamicPropertyDescriptors(attributes);
            }

            return new PropertyDescriptorCollection(props.Cast<PropertyDescriptor>().Concat(other).ToArray());
        }
    }
}